import uuid
from datetime import datetime
from flask import Flask, render_template, request, redirect, url_for, make_response, jsonify
from werkzeug.utils import secure_filename
import os
import cv2
import time
from datetime import timedelta
from preprocess import preprocess_image
from yolov5.predict import predict
from determine import determine
from determine import determinenew
from determine import determinenew_back
from recognition import extract_formatted_text_back
from recognition import extract_formatted_text
from recognition import extract_text
from flask import send_from_directory
import dlib
import face_recognition
import numpy as np  # 导入numpy库
import requests
from io import BytesIO
# 导入 InsightFace 相关库
import insightface
import onnxruntime as ort

# 明确指定使用 CPU 提供者
providers = ['CPUExecutionProvider']

# 获取当前脚本所在的目录
basepath = os.path.dirname(os.path.abspath(__file__))

# 构建模型文件的绝对路径
model_path = os.path.join(basepath, 'workdir/models/buffalo_l/w600k_r50.onnx')

# 检查模型文件是否存在
if not os.path.exists(model_path):
    print(f"Model file {model_path} does not exist.")
    exit(1)

# 加载模型
session = ort.InferenceSession(model_path, providers=providers)
# 加载dlib的人脸检测器
detector = dlib.get_frontal_face_detector()

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp', 'jpeg'])  # 设置允许的文件格式


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


app = Flask(__name__)
app.send_file_max_age_default = timedelta(seconds=1)  # 设置静态文件缓存过期时间

# 初始化 InsightFace 模型
app.face_recognizer = insightface.app.FaceAnalysis(name='buffalo_l', root='workdir')
app.face_recognizer.prepare(ctx_id=0, det_size=(320, 320), det_thresh=0.3)  # 调整检测阈值和图像大小


def resize_image(image, target_size=(640, 640)):
    height, width = image.shape[:2]
    if height < target_size[0] or width < target_size[1]:
        # 放大图片
        image = cv2.resize(image, target_size, interpolation=cv2.INTER_LINEAR)
    return image


@app.route('/api/compare_faces_insight_online', methods=['POST'])
def compare_faces_insight_online():
    try:
        if request.method == 'POST':
            # 获取上传的第一张图片文件和第二张图片的URL
            file1 = request.files.get('file')
            image_url = request.form.get('image_url')

            if not (file1 and image_url):
                return jsonify({"error": 1001, "msg": "请检查上传的图片类型和在线图片URL, 仅限于png、PNG、jpg、JPG、bmp",
                                "status": "error"})

            basepath = os.path.dirname(__file__)  # 当前文件所在源路径
            current_date = datetime.now().strftime('%Y%m%d')
            date_folder = os.path.join(basepath, 'static/images', current_date)
            output_folder = os.path.join(basepath, 'output', current_date)

            # 确保目录存在
            if not os.path.exists(date_folder):
                os.makedirs(date_folder)
            if not os.path.exists(output_folder):
                os.makedirs(output_folder)

            # 保存第一张图片
            uuid1 = uuid.uuid4()
            unique_filename1 = f"{uuid1}{os.path.splitext(file1.filename)[1]}"
            upload_path1 = os.path.join(date_folder, secure_filename(unique_filename1))
            file1.save(upload_path1)

            # 下载第二张图片并保存
            response = requests.get(image_url)
            if response.status_code != 200:
                return jsonify({"error": 1005, "msg": "无法下载在线图片", "status": "error"})

            # 提取图片扩展名
            image_ext = os.path.splitext(image_url)[1].lower()
            if image_ext not in ['.png', '.jpg', '.jpeg', '.bmp']:
                return jsonify(
                    {"error": 1001, "msg": "请检查上传的图片类型, 仅限于png、PNG、jpg、JPG、bmp", "status": "error"})

            image2_content = BytesIO(response.content)
            uuid2 = uuid.uuid4()
            unique_filename2 = f"{uuid2}{image_ext}"
            upload_path2 = os.path.join(date_folder, secure_filename(unique_filename2))
            with open(upload_path2, 'wb') as f:
                f.write(image2_content.getbuffer())

            # 使用 cv2.imread 加载图像并调整尺寸
            img1 = cv2.imread(upload_path1)
            img2 = cv2.imread(upload_path2)

            # 调试信息
            print(f"Image1 loaded: {img1 is not None}")
            print(f"Image2 loaded: {img2 is not None}")

            if img1 is None or img2 is None:
                return jsonify({"error": 1009, "msg": "无法加载上传的图片", "status": "error"})

            # 显示图片尺寸
            print(f"Original Image1 shape: {img1.shape}")
            print(f"Original Image2 shape: {img2.shape}")

            # 调整图片尺寸
            img1 = resize_image(img1)
            img2 = resize_image(img2)

            # 显示调整后的图片尺寸
            print(f"Resized Image1 shape: {img1.shape}")
            print(f"Resized Image2 shape: {img2.shape}")

            # 使用 InsightFace 提取人脸特征
            faces1 = app.face_recognizer.get(img1)
            faces2 = app.face_recognizer.get(img2)

            # 调试信息
            # print(f"Faces detected in file1: {faces1}")
            # print(f"Faces detected in file2: {faces2}")

            if not faces1 or not faces2:
                return jsonify({"error": 1008, "msg": "图片中未检测到人脸", "status": "error"})

            # 获取第一个检测到的人脸的特征向量
            embedding1 = faces1[0].embedding
            embedding2 = faces2[0].embedding

            # 计算两个特征向量之间的余弦相似度
            distance = np.dot(embedding1, embedding2) / (np.linalg.norm(embedding1) * np.linalg.norm(embedding2))

            return jsonify({
                "status": "success",
                "distance": float(distance),  # 余弦相似度
                "are_same_person": bool(distance > 0.3)  # 假设相似度大于0.3认为是同一个人
            })
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({"error": 1004, "msg": f"上传处理过程中出错: {str(e)}", "status": "error"})


@app.route('/api/compare_faces_insight', methods=['POST'])
def compare_faces_insight():
    try:
        if request.method == 'POST':
            # 获取上传的两张图片文件
            file1 = request.files.get('file1')
            file2 = request.files.get('file2')

            if not (file1 and file2 and allowed_file(file1.filename) and allowed_file(file2.filename)):
                return jsonify(
                    {"error": 1001, "msg": "请检查上传的图片类型, 仅限于png、PNG、jpg、JPG、bmp", "status": "error"})

            basepath = os.path.dirname(__file__)  # 当前文件所在源路径
            current_date = datetime.now().strftime('%Y%m%d')
            date_folder = os.path.join(basepath, 'static/images', current_date)
            output_folder = os.path.join(basepath, 'output', current_date)

            # 确保目录存在
            if not os.path.exists(date_folder):
                os.makedirs(date_folder)
            if not os.path.exists(output_folder):
                os.makedirs(output_folder)

            # 保存第一张图片
            uuid1 = uuid.uuid4()
            unique_filename1 = f"{uuid1}{os.path.splitext(file1.filename)[1]}"
            upload_path1 = os.path.join(date_folder, secure_filename(unique_filename1))
            file1.save(upload_path1)

            # 保存第二张图片
            uuid2 = uuid.uuid4()
            unique_filename2 = f"{uuid2}{os.path.splitext(file2.filename)[1]}"
            upload_path2 = os.path.join(date_folder, secure_filename(unique_filename2))
            file2.save(upload_path2)

            # 使用 cv2.imread 加载图像并调整尺寸
            img1 = cv2.imread(upload_path1)
            img2 = cv2.imread(upload_path2)

            # 调试信息
            print(f"Image1 loaded: {img1 is not None}")
            print(f"Image2 loaded: {img2 is not None}")

            if img1 is None or img2 is None:
                return jsonify({"error": 1009, "msg": "无法加载上传的图片", "status": "error"})

            # 显示图片尺寸
            print(f"Original Image1 shape: {img1.shape}")
            print(f"Original Image2 shape: {img2.shape}")

            # 调整图片尺寸
            img1 = resize_image(img1)
            img2 = resize_image(img2)

            # 显示调整后的图片尺寸
            print(f"Resized Image1 shape: {img1.shape}")
            print(f"Resized Image2 shape: {img2.shape}")

            # 使用 InsightFace 提取人脸特征
            faces1 = app.face_recognizer.get(img1)
            faces2 = app.face_recognizer.get(img2)

            # 调试信息
            # print(f"Faces detected in file1: {faces1}")
            # print(f"Faces detected in file2: {faces2}")

            if not faces1 or not faces2:
                return jsonify({"error": 1008, "msg": "图片中未检测到人脸", "status": "error"})

            # 获取第一个检测到的人脸的特征向量
            embedding1 = faces1[0].embedding
            embedding2 = faces2[0].embedding

            # 计算两个特征向量之间的余弦相似度
            distance = np.dot(embedding1, embedding2) / (np.linalg.norm(embedding1) * np.linalg.norm(embedding2))

            token1 = request.form.get('token')
            url1 = request.form.get('url')
            # 如果此请求参数不为空，则向特定的api发送请求，并返回相应结果
            if token1 is not None and token1 != '' and url1 is not None and url1 != '' \
                    and bool(distance > 0.3):
                headers = {'Authorization': f'Bearer {token1}'}
                url = "https://api.gdta.com.cn" + url1 + "/join"

                response = requests.get(url, headers=headers)
                print("url:", url)
                print("token:", token1)
                print("response", response.json())

                return jsonify({
                    "status": "success",
                    "distance": float(distance),  # 余弦相似度
                    "are_same_person": bool(distance > 0.3),
                    "data": response.json()['data']['record_id']
                })

            return jsonify({
                "status": "success",
                "distance": float(distance),  # 余弦相似度
                "are_same_person": bool(distance > 0.3)  # 假设相似度大于0.3认为是同一个人
            })
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({"error": 1004, "msg": f"上传处理过程中出错: {str(e)}", "status": "error"})


@app.route('/', methods=['POST', 'GET'])  # 添加路由
def upload():
    if request.method == 'POST':
        # 删除/static/images里面的所有图像
        target_path = 'static/images'
        for filename in os.listdir(target_path):
            file_path = os.path.join(target_path, filename)
            if os.path.isfile(file_path):
                os.remove(file_path)

        target_path2 = 'output'
        for filename in os.listdir(target_path2):
            file_path = os.path.join(target_path2, filename)
            if os.path.isfile(file_path):
                os.remove(file_path)

        f = request.files['file']

        if not (f and allowed_file(f.filename)):
            return jsonify({"error": 1001, "msg": "请检查上传的图片类型, 仅限于png、PNG、jpg、JPG、bmp"})

        user_input = request.form.get("name")

        basepath = os.path.dirname(__file__)  # 当前文件所在源路径

        upload_path = os.path.join(basepath, 'static/images',
                                   secure_filename(f.filename))  # 另存路径:static/image/{filename}
        f.save(upload_path)

        top, bottom, left, right = predict(upload_path)
        points = [top, bottom, left, right]

        img = cv2.imread(upload_path)  # 处理的图像
        gray_img, img = preprocess_image(img, points)  # preprocess

        size = img.shape
        img = cv2.resize(img, (int(size[1] / 2), int(size[0] / 2)), interpolation=cv2.INTER_AREA)
        cropped_image_relative_path = os.path.join('static/images', f'test_{secure_filename(f.filename)}')
        cropped_image_path = os.path.join(basepath, cropped_image_relative_path)
        cv2.imwrite(cropped_image_path, img)

        determine(gray_img)
        text = extract_text()
        print(text)
        # 上传文字
        products = text
        return render_template('upload_ok.html', userinput=user_input, val1=time.time(), products=products)

    return render_template('upload.html')


@app.route('/api/upload', methods=['POST'])
def api_upload():
    try:
        if request.method == 'POST':
            f = request.files.get('file')

            if not (f and allowed_file(f.filename)):
                return jsonify(
                    {"error": 1001, "msg": "请检查上传的图片类型, 仅限于png、PNG、jpg、JPG、bmp", "status": "error"})

            basepath = os.path.dirname(__file__)  # 当前文件所在源路径
            current_date = datetime.now().strftime('%Y%m%d')
            date_folder = os.path.join(basepath, 'static/images', current_date)
            output_folder = os.path.join(basepath, 'output', current_date)

            # 确保目录存在
            if not os.path.exists(date_folder):
                os.makedirs(date_folder)
            if not os.path.exists(output_folder):
                os.makedirs(output_folder)

            uuids = uuid.uuid4()
            unique_filename = f"{uuids}{os.path.splitext(f.filename)[1]}"
            upload_path = os.path.join(date_folder, secure_filename(unique_filename))
            f.save(upload_path)

            print(f"upload_path={upload_path}")

            # 调用 predict 并处理返回值
            try:
                result = predict(upload_path)
                if isinstance(result, tuple) and len(result) == 4:
                    top, bottom, left, right = result
                else:
                    return jsonify({"error": 1002, "msg": "预测函数返回值格式不正确", "status": "error"})
            except Exception as e:
                return jsonify({"error": 1003, "msg": f"预测函数执行出错: {str(e)}", "status": "error"})

            points = [top, bottom, left, right]

            img = cv2.imread(upload_path)
            gray_img, img = preprocess_image(img, points)

            size = img.shape
            img = cv2.resize(img, (int(size[1] / 2), int(size[0] / 2)), interpolation=cv2.INTER_AREA)
            cropped_image_relative_path = os.path.join('static/images', current_date, f'test_{unique_filename}')
            cropped_image_path = os.path.join(basepath, cropped_image_relative_path)
            cv2.imwrite(cropped_image_path, img)

            determinenew(gray_img, current_date, uuids)
            text, count = extract_formatted_text(current_date, uuids)
            print(text)
            print(count)
            if count != 7:
                return jsonify({
                    "error": 1005, "msg": f"身份证信息识别失败。", "status": "error"
                })
            else:
                # 人脸检测和保存
                face_img = cv2.imread(cropped_image_path)
                gray_face_img = cv2.cvtColor(face_img, cv2.COLOR_BGR2GRAY)
                faces = detector(gray_face_img)

                if len(faces) > 0:
                    # 假设我们只处理检测到的第一个人脸
                    face = faces[0]
                    x, y, w, h = face.left(), face.top(), face.width(), face.height()
                    face_roi = face_img[y:y + h, x:x + w]

                    face_filename = f'tx_{uuids}.png'
                    face_folder = os.path.join(basepath, 'static/images', current_date)
                    face_path = os.path.join(face_folder, face_filename)
                    cv2.imwrite(face_path, face_roi)

                    face_relative_path = os.path.join('static/images', current_date, face_filename)
                    return jsonify({
                        "status": "success",
                        "data": text,
                        "cropped_image_path": os.path.normpath(cropped_image_relative_path).replace('\\', '/'),
                        "face_image_path": os.path.normpath(face_relative_path).replace('\\', '/')
                    })
                else:
                    return jsonify({
                        "status": "success",
                        "data": text,
                        "cropped_image_path": os.path.normpath(cropped_image_relative_path).replace('\\', '/'),
                        "face_image_path": None
                    })
    except Exception as e:
        print(e)
        return jsonify({"error": 1004, "msg": f"上传处理过程中出错: {str(e)}", "status": "error"})


@app.route('/api/upload_back', methods=['POST'])
def api_upload_back():
    try:
        if request.method == 'POST':
            f = request.files.get('file')

            if not (f and allowed_file(f.filename)):
                return jsonify(
                    {"error": 1001, "msg": "请检查上传的图片类型, 仅限于png、PNG、jpg、JPG、bmp", "status": "error"})

            basepath = os.path.dirname(__file__)  # 当前文件所在源路径
            current_date = datetime.now().strftime('%Y%m%d')
            date_folder = os.path.join(basepath, 'static/images', current_date)
            output_folder = os.path.join(basepath, 'output', current_date)

            # 确保目录存在
            if not os.path.exists(date_folder):
                os.makedirs(date_folder)
            if not os.path.exists(output_folder):
                os.makedirs(output_folder)

            uuids = uuid.uuid4()
            unique_filename = f"{uuids}{os.path.splitext(f.filename)[1]}"
            upload_path = os.path.join(date_folder, secure_filename(unique_filename))
            f.save(upload_path)

            # 调用 predict 并处理返回值
            try:
                result = predict(upload_path)
                if isinstance(result, tuple) and len(result) == 4:
                    top, bottom, left, right = result
                else:
                    return jsonify({"error": 1002, "msg": "预测函数返回值格式不正确", "status": "error"})
            except Exception as e:
                return jsonify({"error": 1003, "msg": f"预测函数执行出错: {str(e)}", "status": "error"})

            points = [top, bottom, left, right]

            img = cv2.imread(upload_path)
            gray_img, img = preprocess_image(img, points)

            size = img.shape
            img = cv2.resize(img, (int(size[1] / 2), int(size[0] / 2)), interpolation=cv2.INTER_AREA)
            cropped_image_relative_path = os.path.join('static/images', current_date, f'test_back_{unique_filename}')
            cropped_image_path = os.path.join(basepath, cropped_image_relative_path)
            cv2.imwrite(cropped_image_path, img)

            # 调用新的处理函数
            determinenew_back(gray_img, current_date, uuids)
            text, count = extract_formatted_text_back(current_date, uuids)
            print(text)
            print(count)
            if count != 2:  # 假设背面信息有2个字段
                return jsonify({
                    "error": 1005, "msg": f"身份证背面信息识别失败。", "status": "error"
                })
            else:
                return jsonify({
                    "status": "success",
                    "data": text,
                    "cropped_image_path": os.path.normpath(cropped_image_relative_path).replace('\\', '/')
                })
    except Exception as e:
        print(f"上传处理过程中出错: {str(e)}")
        return jsonify({"error": 1004, "msg": f"上传处理过程中出错: {str(e)}", "status": "error"})


@app.route('/images/<path:filename>', methods=['GET'])
def serve_image(filename):
    # 确定文件路径
    if filename.startswith('output/'):
        directory = 'output'
        file_path = os.path.join(directory, filename[len('output/'):])
    elif filename.startswith('static/images/'):
        directory = 'static/images'
        file_path = os.path.join(directory, filename[len('static/images/'):])
    else:
        return jsonify({"error": 1006, "msg": "文件路径不正确", "status": "error"}), 400

    print(file_path)
    # 检查文件是否存在
    if not os.path.isfile(file_path):
        return jsonify({"error": 1007, "msg": "文件不存在", "status": "error"}), 404

    # 发送文件
    return send_from_directory(directory, filename[len(directory) + 1:])


# 新增的API接口，用于比较两张图片中的人脸是否是同一个人
@app.route('/api/compare_faces', methods=['POST'])
def compare_faces():
    try:
        if request.method == 'POST':
            # 获取上传的两张图片文件
            file1 = request.files.get('file1')
            file2 = request.files.get('file2')

            if not (file1 and file2 and allowed_file(file1.filename) and allowed_file(file2.filename)):
                return jsonify(
                    {"error": 1001, "msg": "请检查上传的图片类型, 仅限于png、PNG、jpg、JPG、bmp", "status": "error"})

            basepath = os.path.dirname(__file__)  # 当前文件所在源路径
            current_date = datetime.now().strftime('%Y%m%d')
            date_folder = os.path.join(basepath, 'static/images', current_date)
            output_folder = os.path.join(basepath, 'output', current_date)

            # 确保目录存在
            if not os.path.exists(date_folder):
                os.makedirs(date_folder)
            if not os.path.exists(output_folder):
                os.makedirs(output_folder)

            # 保存第一张图片
            uuid1 = uuid.uuid4()
            unique_filename1 = f"{uuid1}{os.path.splitext(file1.filename)[1]}"
            upload_path1 = os.path.join(date_folder, secure_filename(unique_filename1))
            file1.save(upload_path1)

            # 保存第二张图片
            uuid2 = uuid.uuid4()
            unique_filename2 = f"{uuid2}{os.path.splitext(file2.filename)[1]}"
            upload_path2 = os.path.join(date_folder, secure_filename(unique_filename2))
            file2.save(upload_path2)

            # 加载图片并识别人脸
            image1 = face_recognition.load_image_file(upload_path1)
            image2 = face_recognition.load_image_file(upload_path2)

            face_encodings1 = face_recognition.face_encodings(image1)
            face_encodings2 = face_recognition.face_encodings(image2)

            if len(face_encodings1) == 0 or len(face_encodings2) == 0:
                return jsonify({"error": 1008, "msg": "图片中未检测到人脸", "status": "error"})

            # 比较人脸
            face_encoding1 = face_encodings1[0]
            face_encoding2 = face_encodings2[0]
            distance = face_recognition.face_distance([face_encoding1], face_encoding2)[0]

            # 添加调试信息
            print(f"Face encoding 1: {face_encoding1}")
            print(f"Face encoding 2: {face_encoding2}")
            print(f"Distance: {distance}")

            token1 = request.form.get('token')
            url1 = request.form.get('url')
            # 如果此请求参数不为空，则向特定的api发送请求，并返回相应结果
            if token1 is not None and token1 != '' and url1 is not None and url1 != '' \
                    and bool(face_recognition.compare_faces([face_encoding1], face_encoding2)[0]):
                headers = {'Authorization': f'Bearer {token1}'}
                url = "https://api.gdta.com.cn" + url1 + "/join"

                response = requests.get(url, headers=headers)
                print("url:", url)
                print("token:", token1)
                print("response", response.json())

                return jsonify({
                    "status": "success",
                    "distance": float(distance),  # 确保返回的浮点数可以被正确序列化
                    "are_same_person": bool(face_recognition.compare_faces([face_encoding1], face_encoding2)[0]),
                    "data": response.json()['data']['record_id']
                })

            return jsonify({
                "status": "success",
                "distance": float(distance),  # 确保返回的浮点数可以被正确序列化
                "are_same_person": bool(face_recognition.compare_faces([face_encoding1], face_encoding2)[0])
            })
    except Exception as e:
        return jsonify({"error": 1004, "msg": f"上传处理过程中出错: {str(e)}", "status": "error"})


@app.route('/api/compare_faces_online', methods=['POST'])
def compare_faces_online():
    try:
        if request.method == 'POST':
            # 获取上传的第二张图片文件和第一张图片的URL
            file2 = request.files.get('file')
            image_url = request.form.get('image_url')

            if not (file2 and allowed_file(file2.filename) and image_url):
                return jsonify({"error": 1001, "msg": "请检查上传的图片类型和在线图片URL, 仅限于png、PNG、jpg、JPG、bmp",
                                "status": "error"})

            basepath = os.path.dirname(__file__)  # 当前文件所在源路径
            current_date = datetime.now().strftime('%Y%m%d')
            date_folder = os.path.join(basepath, 'static/images', current_date)
            output_folder = os.path.join(basepath, 'output', current_date)

            # 确保目录存在
            if not os.path.exists(date_folder):
                os.makedirs(date_folder)
            if not os.path.exists(output_folder):
                os.makedirs(output_folder)

            # 下载第一张图片并保存
            response = requests.get(image_url)
            if response.status_code != 200:
                return jsonify({"error": 1005, "msg": "无法下载在线图片", "status": "error"})

            # 提取图片扩展名
            image_ext = os.path.splitext(image_url)[1].lower()
            if image_ext not in ['.png', '.jpg', '.jpeg', '.bmp']:
                return jsonify(
                    {"error": 1001, "msg": "请检查上传的图片类型, 仅限于png、PNG、jpg、JPG、bmp", "status": "error"})

            image1_content = BytesIO(response.content)
            uuid1 = uuid.uuid4()
            unique_filename1 = f"{uuid1}{image_ext}"
            upload_path1 = os.path.join(date_folder, secure_filename(unique_filename1))
            with open(upload_path1, 'wb') as f:
                f.write(image1_content.getbuffer())

            # 保存第二张图片
            uuid2 = uuid.uuid4()
            unique_filename2 = f"{uuid2}{os.path.splitext(file2.filename)[1]}"
            upload_path2 = os.path.join(date_folder, secure_filename(unique_filename2))
            file2.save(upload_path2)

            # 加载图片并识别人脸
            image1 = face_recognition.load_image_file(upload_path1)
            image2 = face_recognition.load_image_file(upload_path2)

            face_encodings1 = face_recognition.face_encodings(image1)
            face_encodings2 = face_recognition.face_encodings(image2)

            if len(face_encodings1) == 0 or len(face_encodings2) == 0:
                return jsonify({"error": 1008, "msg": "图片中未检测到人脸", "status": "error"})

            # 比较人脸
            face_encoding1 = face_encodings1[0]
            face_encoding2 = face_encodings2[0]
            distance = face_recognition.face_distance([face_encoding1], face_encoding2)[0]

            # 添加调试信息
            print(f"Face encoding 1: {face_encoding1}")
            print(f"Face encoding 2: {face_encoding2}")
            print(f"Distance: {distance}")

            return jsonify({
                "status": "success",
                "distance": float(distance),  # 确保返回的浮点数可以被正确序列化
                "are_same_person": bool(face_recognition.compare_faces([face_encoding1], face_encoding2)[0])

            })
    except Exception as e:
        return jsonify({"error": 1004, "msg": f"上传处理过程中出错: {str(e)}", "status": "error"})


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8987, debug=True)